package cn.wolfcode.shop.cloud.member.reslove;

import cn.wolfcode.shop.cloud.member.domain.User;

import cn.wolfcode.shop.cloud.member.util.MemberKeyPrefix;
import cn.wolfcode.shop.cloud.member.util.ParamType;
import cn.wolfcode.shop.cloud.service.RedisService;
import cn.wolfcode.shop.cloud.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;


public class UserArgumentsResolver implements HandlerMethodArgumentResolver {
    @Autowired
    RedisService redisService;
    /**
     * 判断你当前参数的类型
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return  methodParameter.getParameterAnnotation(ParamType.class) != null &&
                methodParameter.getParameterType() == User.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        //从请求中获取token
        String token = CookieUtil.getCookieValue(request, "userToken");
        //从redis取值
        User user = redisService.get(MemberKeyPrefix.USER_TOKEN,token,User.class);
        return user;
    }
}
